package com.urtime.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.json.simple.JSONObject;

import com.urtime.model.Event;
import com.urtime.model.User;
import com.urtime.util.ErrorJson;
import com.urtime.util.HibernateUtil;

public class EventDAO {
	static public boolean validateEvent(Event e){
		return true;
	}
	static public int addEvent(Event event){
		if(!validateEvent(event)){
			return ErrorJson.ERROR_PARAMS;
		}
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        try{
	        session.beginTransaction();
	        session.save(event);
	        session.getTransaction().commit();
	        return ErrorJson.ERROR_OK;
        }catch(Exception e){
        	session.getTransaction().rollback();
        	e.printStackTrace();
        	return ErrorJson.ERROR_UNKNOWN;
        }
		
	}
	
	static public int addEventToUser(int userid, Event ev){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try{
			session.beginTransaction();
			User user = (User) session.load(User.class, userid);
			if(user==null){
				return ErrorJson.ERROR_UNKNOWN_USER;
			}
			ev.setOwner(user);
			session.save(ev);
			user.getEvents().add(ev);
			//session.update(user);
			session.getTransaction().commit();
			return ErrorJson.ERROR_OK;
		}catch(Exception e){
			e.printStackTrace();
			session.getTransaction().rollback();
		}		
		return ErrorJson.ERROR_UNKNOWN;
		
	}
	
	static public Set<Event> listEventOfUser(int userid){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try{
			session.beginTransaction();
			User user = (User) session.load(User.class, userid);
			if(user==null){
				return null;
			}
			//System.out.println(user.getEvents().size());
			return user.getEvents();
			//session.getTransaction().commit();
			//return null;
		}catch(Exception e){
			//e.printStackTrace();
			session.getTransaction().rollback();
		}		
		return null;		
	}
	
	static public List<Event> queryEventByUser(int userid, String cond){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try{
			session.beginTransaction();
			User user = (User) session.load(User.class, userid);
			if(user==null){
				return null;
			}
			//System.out.println(user.getEvents().size());
			List<Event> result = 
					(List<Event>) session.createQuery("FROM Event WHERE USER_ID="+userid+" "+cond).list();
			//session.getTransaction().commit();
			return result;
			//return null;
		}catch(Exception e){
			e.printStackTrace();
			session.getTransaction().rollback();
		}		
		return null;		
	}
	
	static public JSONObject eventToJson(Event ev){
		JSONObject obj = new JSONObject();
		obj.put("id", ev.getId());
		obj.put("isBusy", ev.getIsBusy());
		obj.put("description", ev.getDescription());
		return obj;
	}
}
